// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const username = event.username
  // 修改 user 中的 username 和 avatarUrl
  const usersDb = cloud.database().collection('users')
  const userData = await usersDb.where({
    openid
  }).get()
  const user = userData.data[0]
  delete user._id
  user.username = event.username
  // 获取下载地址
  let avatarUrl = ''
  if (event.avatarId) {
    const fileID = event.avatarId
    const res = await cloud.getTempFileURL({
      fileList: [fileID]
    })
    avatarUrl = res.fileList[0].tempFileURL
    user.avatarUrl = avatarUrl
  }
  await usersDb.where({
    openid
  }).update({
    data: user
  })
  if (avatarUrl) {
    return {
      avatarUrl,
      username
    }
  } else {
    return { username }
  }
}